const util = require('util');
const debug = util.debuglog('oil-game:upgrade:dao');

const upgradeSchema = require('./upgradeSchema');
const Level = require('../../../domain/level');

// 初始化升级信息数据表
exports.initUpgradeByMongo = function (uid) {
    debug("用户 " + uid + " 初始化升级信息");
    return new Promise((resolve, reject) => {
        new upgradeSchema({uid}).save(function (err, data) {
            if (err) {
                debug("用户 " + uid + " 初始化升级信息出错" + JSON.stringify(err));
                return reject(err);
            }
            debug("用户 " + uid + " 初始化升级信息，结果" + data);
            resolve(data);
        });
    });
}

// 查询用户升级信息
exports.getUpgradeByMongo = function (uid) {
    debug("用户 " + uid + " 获取升级信息");
    return new Promise((resolve, reject) => {
        upgradeSchema.findOne({uid}, function (err, data) {
            if (err) {
                debug("用户 " + uid + " 获取升级信息出错" + JSON.stringify(err));
                return reject(err);
            }
            debug("用户 %s 获取升级信息，结果 %s ", uid, JSON.stringify(data));
            resolve(data && data.toObject());
        });
    });
}

// 保存用户升级信息
exports.updateUpgrade = function (upgrade) {
    debug("更新升级信息 %s", JSON.stringify(upgrade));
    return new Promise((resolve, reject) => {
        upgradeSchema.updateOne({uid: upgrade.uid}, upgrade, function (err, data) {
            if (err) {
                debug("更新升级信息出错 %s", JSON.stringify(err));
                return reject(err);
            }
            debug("更新升级信息成功 %s ", JSON.stringify(data));
            resolve(data);
        });
    });
}

//获取矿层信息
exports.getLevelInfo = function (uid) {
    return new Promise((resolve, reject) => {
        Level.find({uid: uid}, function (err, data) {
            if (err) {
                return reject(err);
            }
            return resolve(data);
        }).sort({'level_num': 1});
    });
}
